package cn.wolfcode.crm.realm;

import cn.wolfcode.crm.domain.Operator;
import cn.wolfcode.crm.mapper.OperatorMapper;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.mapper.RoleMapper;
import lombok.Setter;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.List;

//shirode 自定义realm
public class UserRealm extends AuthorizingRealm {
    @Setter
    private OperatorMapper operatorMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    public String getName() {
        return "userRealm";
    }


    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Operator operator = (Operator)principals.getPrimaryPrincipal();
        //根据用户名获取权限名
        List<String> roleName=null;
        //根据用户名获取权限列表
        List<String> permissonResources=null;
        if(operator.getAdmin()==Operator.STATE_ADMIN){
            roleName=roleMapper.allRoleName();
            permissonResources= Arrays.asList("*:*");
        }else {
            roleName=roleMapper.listRoleNameByOperatorId(operator.getId());
            permissonResources= permissionMapper.listPermissionByOperatorId(operator.getId());
        }
        //封装到AuthorizationInfo中
        SimpleAuthorizationInfo inf=new SimpleAuthorizationInfo();
        inf.addRoles(roleName);
        inf.addStringPermissions(permissonResources);
        return inf;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        try {
            //获取当前的用户名
            String username = (String) token.getPrincipal();

            Operator current = operatorMapper.queryByName(username);
            if (current == null) {
                //如果不是null的话,就执新
                return null;
            }
            SimpleAuthenticationInfo info =
                    new SimpleAuthenticationInfo(current,current.getPassword(), ByteSource.Util.bytes(current.getUsername()), getName());

            return info;//返回info的信息
            
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
